package com.hmall.item.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.Utils.BaseContext;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ItemService extends ServiceImpl<ItemMapper, Item> implements IItemService {
    @Autowired
    private ItemMapper itemMapper;

    /**
     * 商品分页查询功能
     *
     * @param page
     * @param size
     * @return
     */
    @Override
    public PageDTO pageList(Integer page, Integer size) {

        IPage<Item> itemPage = new Page<>(page, size);
        IPage<Item> list = itemMapper.selectPage(itemPage, null);

        List<Item> records = list.getRecords();

        long total = list.getTotal();

        PageDTO pageDTO = new PageDTO();
        pageDTO.setTotal(total);
        pageDTO.setList(records);

        Long userId = BaseContext.getCurrentId();
        log.error("用户为：{}",userId);

        return pageDTO;
    }

    /**
     * 通过id获取商品
     *
     * @param id
     * @return
     */
    @Override
    public Item getItemById(Long id) {
        Item item = itemMapper.selectById(id);
        return item;
    }

    /**
     * 新增商品
     *
     * @param item
     * @return
     */
    @Override
    public boolean add(Item item) {
        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        int rows = itemMapper.insert(item);
        return rows > 0;
    }

    /**
     * 商品上架/下架功能
     *
     * @param id
     * @param status
     * @return
     */
    @Override
    public boolean setStatus(Long id, Integer status) {
        Item item = new Item();
        item.setStatus(status);
        item.setId(id);

        int rows = itemMapper.updateById(item);

        return rows == 1;
    }

    /**
     * 根据id删除商品
     *
     * @param id
     * @return
     */
    @Override
    public boolean deleteItem(Long id) {
        int rows = itemMapper.deleteById(id);
        return rows > 0;
    }

    @Override
    public boolean updateItem(Item item) {
        item.setUpdateTime(new Date());
        int rows = itemMapper.updateById(item);
        System.out.println("rows = " + rows);
        return rows > 0;
    }
}
